package com.onec.service.io.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NioDisCardService {

  public static void startService() throws IOException {
    Selector selector = Selector.open();
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(8852));
    // 通道注册到选择
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (selector.select() > 0) {
      Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();

      while (selectionKeyIterator.hasNext()) {
        SelectionKey selectionKey = selectionKeyIterator.next();
        // 新建立的客户端传输通道：注册到同一个选择器上
        if (selectionKey.isAcceptable()) {
          SocketChannel socketChannel = serverSocketChannel.accept();
          socketChannel.configureBlocking(false);
          socketChannel.register(selector, SelectionKey.OP_READ);

        } else if (selectionKey.isReadable()) {
          SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
          ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
          int length = 0;
          while ((length = socketChannel.read(byteBuffer)) > 0) {
            byteBuffer.flip();
            System.out.println(new String(byteBuffer.array(), 0, length));
            byteBuffer.clear();
          }
          socketChannel.close();
        }
        selectionKeyIterator.remove();
      }
    }
    serverSocketChannel.close();
  }

  public static void main(String[] args) throws IOException {
    startService();
  }
}
